package com.boot.app.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.aop.LoggerType;
import com.boot.aop.SystemLogger;
import com.boot.api.ApiResult;
import com.boot.app.base.domain.BaseRole;
import com.boot.app.base.service.IBaseRoleService;
import com.boot.app.base.vo.RoleVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@SystemLogger(objectClass = BaseRole.class)
@RestController
@RequestMapping("base/role")
public class BaseRoleController {

    private final IBaseRoleService service;

    @Autowired
    public BaseRoleController(IBaseRoleService service){
        this.service = service;
    }

    @GetMapping("{id}")
    public ApiResult<BaseRole> getRole(@PathVariable("id") long id){
        BaseRole role = service.getById(id);
        return ApiResult.success(role);
    }

    @GetMapping("list")
    public ApiResult<List<BaseRole>> getRoleList(){
        List<BaseRole> roleList = service.list();
        return ApiResult.success(roleList);
    }

    @GetMapping("page/{page}/{size}")
    public ApiResult<Page<RoleVO>> getRolePage(@PathVariable("page")int page, @PathVariable("size")int size, BaseRole role){
        LambdaQueryWrapper<BaseRole> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(role.getName())) wrapper.like(BaseRole::getName, role.getName());
        Page<RoleVO> rolePage = new Page<>(page, size);
        rolePage = service.pageRoleVO(rolePage, wrapper);
        return ApiResult.success(rolePage);
    }

    @SystemLogger(type = { LoggerType.INSERT, LoggerType.UPDATE })
    @PostMapping()
    public ApiResult<?> postOrPutRole(@RequestBody BaseRole role){
        service.saveOrUpdate(role);
        return ApiResult.success();
    }

    @SystemLogger(type = LoggerType.DELETE, objectClass = BaseRole.class)
    @DeleteMapping("{id}")
    public ApiResult<?> deleteRole(@PathVariable("id") long id){
        service.removeById(id);
        return ApiResult.success();
    }

    @GetMapping("listByUserId/{userId}")
    public ApiResult<List<BaseRole>> getRoleListByUserId(@PathVariable("userId") long userId){
        List<BaseRole> list = service.fetchListByUserId(userId);
        return ApiResult.success(list);
    }

}
